package com.lik888.config;

import cn.hutool.jwt.JWTUtil;
import com.lik888.filter.JWTAuthenticationfilter;
import com.lik888.handler.AnonymousAuthenticationHandler;
import com.lik888.handler.CustomerAccessDeniedHandler;
import com.lik888.handler.LoginFailureHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.ConversionService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.security.KeyPair;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    // 注入你自己写的 UserDetailsService（查数据库拿用户的逻辑）
    private final UserDetailsService userDetailsService;

    @Autowired
    private  JWTAuthenticationfilter jwtAuthenticationfilter;

    @Autowired
    private CustomerAccessDeniedHandler customerAccessDeniedHandler;


     @Autowired
    private AnonymousAuthenticationHandler anonymousAuthenticationHandler;

     @Autowired
     private LoginFailureHandler loginFailureHandler;


    // 构造器注入，不用@Autowired
    public SecurityConfig(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    // 1. 定义 BCrypt 密码编码器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 2. 关键：把编码器和用户查询服务绑定到认证提供者
    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService); // 关联查用户的逻辑
        provider.setPasswordEncoder(passwordEncoder()); // 关联编码器（解决错误的核心）
        return provider;
    }

    // 3. 认证管理器（固定写法，依赖上面的认证提供者）
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

    // 4. 配置接口权限（放行登录接口，其他需认证）
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http, ConversionService conversionService) throws Exception {
        http
                .csrf(csrf -> csrf.disable()) // 前后端分离必关，否则登录失败
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/user/login").permitAll() // 登录接口放行
                        .anyRequest().authenticated() // 其他接口需登录
                )
                .formLogin(form -> form.permitAll().failureHandler(loginFailureHandler)

                ); // 允许访问默认登录页

        // 把认证提供者加入流程（必须加，否则上面的配置不生效）
        http.authenticationProvider(authenticationProvider());

        http.addFilterBefore(jwtAuthenticationfilter, UsernamePasswordAuthenticationFilter.class);

        http.exceptionHandling(configurer ->{
            configurer.accessDeniedHandler(customerAccessDeniedHandler);
            configurer.authenticationEntryPoint(anonymousAuthenticationHandler);

        }


        );

        return http.build();
    }


}


////        // 和配置中一样的 BCrypt 编码器
////        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
////        String rawPassword = "123456"; // 用户的原始密码（登录时输这个）
////        String encodedPassword = encoder.encode(rawPassword);
////        // 输出示例：$2a$10$abcdefghijklmnopqrstuXXXXXXXXXXXXXXXXXXXXX
////        System.out.println("BCrypt 密码：" + encodedPassword);
//        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//        String password = user.getPassword();
//        return encoder.encode(password);